.set DISTANCE,0x80



.set PORT_DISK1_DATA  , (0x1f0-DISTANCE)
.set PORT_DISK1_ERR_FEATURE , 0x1f1-DISTANCE
.set PORT_DISK1_SECTOR_CNT  ,0x1f2 - DISTANCE
.set PORT_DISK1_SECTOR_LOW  ,0x1f3 - DISTANCE
.set PORT_DISK1_SECTOR_MID , 0x1f4 - DISTANCE
.set PORT_DISK1_SECTOR_HIGH , 0x1f5 - DISTANCE
.set PORT_DISK1_DEVICE , 0x1f6 - DISTANCE
.set PORT_DISK1_STATUS_CMD , 0x1f7 - DISTANCE
.set PORT_DISK1_ALT_STA_CTL , 0x3f6 - DISTANCE


    
.global testDisk
testDisk:
  test:
    
    
    movq $0x1,count(%rip)
    movq $0x0,sector(%rip)
    xor %rsi,%rsi
    leaq bufferTest(%rip),%rsi
    call readDisk
    


initDiskDriver:
    movw $PORT_DISK1_ALT_STA_CTL,%dx
    movb $0,%al
    outb %al,%dx

    call waitDiskNotBusy

    movw $PORT_DISK1_ERR_FEATURE,%dx
    movb $0,%al
    outb %al,%dx

    movw $PORT_DISK1_SECTOR_CNT,%dx
    movb count(%rip),%al
    outb %al,%dx

    movw $PORT_DISK1_SECTOR_LOW,%dx
    movl sector(%rip),%ebx
    andl $0xff,%ebx
    movb %bl,%al
    outb %al,%dx

    movw $PORT_DISK1_SECTOR_MID,%dx
    movl sector(%rip),%ebx
    shrl $8,%ebx
    andl $0xff,%ebx
    movb %bl,%al
    outb %al,%dx   

    movw $PORT_DISK1_SECTOR_HIGH,%dx
    movl sector(%rip),%ebx
    shrl $16,%ebx
    andl $0xff,%ebx
    movb %bl,%al
    outb %al,%dx   


    movw $PORT_DISK1_DEVICE,%dx
    movl sector(%rip),%ebx
    shrl $24,%ebx
    andl $0xf,%ebx
    orl $0x0e0,%ebx
    movb %bl,%al
    outb %al,%dx   

    call waitDiskReady

    mov $PORT_DISK1_STATUS_CMD,%dx
    mov $0x20,%al
    outb %al,%dx

    ret


readDisk:
    call initDiskDriver
    call waitDiskReady
    call waitDiskReq
    xchg %bx,%bx
    movw $256,%cx
read:    
    cmp $0,%cx
    jz readFinish
    movw $PORT_DISK1_DATA,%dx
    inw %dx,%ax
    nop
    nop
    nop
    movw %ax,(%rsi)
    xchg %bx,%bx
test1:
    jmp test1
    addq $2,%rsi

    decw %cx
    jmp read
readFinish:
    nop ; 一点点延迟:
    nop
    nop
    ret

waitDiskReady:
    movw $PORT_DISK1_STATUS_CMD,%dx
    inb %dx, %al
    nop
    nop
    nop
    andb $0b01000000, %al
    jz waitDiskReady
    ret



waitDiskNotBusy:
    movw $PORT_DISK1_STATUS_CMD, %dx
    inb %dx, %al
    nop
    nop
    nop
    andb $0b10000000, %al
    jnz waitDiskNotBusy
    ret

waitDiskReq:
    movw $PORT_DISK1_STATUS_CMD,%dx
    inb %dx, %al
    nop
    nop
    nop
    andb $0b00001000, %al
    jz waitDiskReq
    ret





    count: .byte 0x00
    sector: .long 0x00000000

    msg: .string "start boot"
    